package com.ccys.cms.service.masterData.impl;

import cn.hutool.core.util.ObjectUtil;
import com.ccys.cms.service.masterData.MedicationUsagePeriodService;
import com.ccys.common.vo.ResponseResult;
import com.ccys.db.dto.masterData.MedicationUsagePeriodDelDto;
import com.ccys.db.dto.masterData.MedicationUsagePeriodPageQueryDto;
import com.ccys.db.dto.masterData.MedicationUsagePeriodSaveDto;
import com.ccys.db.entity.TblMedicationUsagePeriod;
import com.ccys.db.mapper.TblMedicationUsagePeriodMapper;
import com.ccys.db.page.PageDto;
import com.ccys.db.rely.service.impl.BaseServiceImpl;
import com.ccys.db.service.BaseTblAuditTrailWebService;
import com.ccys.db.vo.masterData.MedicationUsagePeriodPageVo;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;
import java.util.Optional;

/**
 * @program: WhiteCoat
 * @description: 用药周期实现类
 * @author: ZhangJingCan
 * @create: 2023-12-12 09:11
 **/

@Service
public class MedicationUsagePeriodServiceImpl extends BaseServiceImpl<TblMedicationUsagePeriod> implements MedicationUsagePeriodService {

    @Resource
    private TblMedicationUsagePeriodMapper tblMedicationUsagePeriodMapper;

    /**
     * 用于保存修改状态日志
     */
    @Autowired(required = false)
    private BaseTblAuditTrailWebService baseTblAuditTrailWebService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult save(MedicationUsagePeriodSaveDto dto) {
        //如果名称和集团ID都不为空 - 则需要校验数据库是否存在
        if (ObjectUtil.isNotEmpty(dto.getName()) && ObjectUtil.isNotEmpty(dto.getGroupId())) {
            //查询：名称+集团 - 未删除数据是否存在 - 存在则不保存
            Example example = new Example(TblMedicationUsagePeriod.class);
            example.createCriteria()
                    .andEqualTo("name", dto.getName())
                    .andEqualTo("groupId", dto.getGroupId())
                    .andEqualTo("delFlag", 0);
            //这里还需要判断 - 如果ID不为空 - 属于修改 - 需要判断不等于当前ID
            if (ObjectUtil.isNotEmpty(dto.getId())) {
                //加入条件 - ID不等于当前ID
                example.createCriteria().andNotEqualTo("id", dto.getId());
            }
            //查询并判断，有值则返回错误信息
            if (ObjectUtil.isNotEmpty(tblMedicationUsagePeriodMapper.selectOneByExample(example))) {
                return ResponseResult.error("The name already exists in the current group!");
            }
        }
        if (ObjectUtil.isNotEmpty(dto.getId()) && ObjectUtil.isNotEmpty(dto.getStatus())) {
            baseTblAuditTrailWebService.saveStatusLog(dto, dto.getStatus());
        }
        //保存或修改 - 并判断是否成功 - 并返回
        return ResponseResult.update(this.insertOrUpdate(dto));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult delete(MedicationUsagePeriodDelDto dto) {
        //校验参数
        if (ObjectUtil.isEmpty(dto.getId())) {
            return ResponseResult.error("Parameter Error!");
        }
        //准备参数
        TblMedicationUsagePeriod period = new TblMedicationUsagePeriod();
        period.setId(dto.getId());
        period.setDelFlag(1);
        if (tblMedicationUsagePeriodMapper.updateByPrimaryKeySelective(period) > 0) {
            return ResponseResult.success("Delete Successful!");
        }
        return ResponseResult.error("Delete Failed!");
    }

    @Override
    public ResponseResult findPage(MedicationUsagePeriodPageQueryDto dto) {
        //检查并设置初始值 - 如果status 的值不在0/1 则设置为null
        dto.setStatus(Optional.ofNullable(dto.getStatus()).filter(s -> s > -1 && s < 2).orElse(null));
        PageDto.startPage();
        PageInfo<MedicationUsagePeriodPageVo> info = new PageInfo<>(tblMedicationUsagePeriodMapper.findPage(dto));
        return ResponseResult.success(info);
    }
}
